package com.it.tydic.estate.module.controller.common;

import com.it.tydic.estate.common.annotation.ControllerDesc;
import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import com.it.tydic.estate.common.constants.LogConstants;
import com.it.tydic.estate.common.security.MyPasswordEncoder;
import com.it.tydic.estate.module.model.inner.TbUser;
import com.it.tydic.estate.module.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.util.StringUtil;

import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("user")
@Api(tags = "用户管理接口")
public class UserController {

    @Autowired
    private UserService userService;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    @PostMapping("/findAllByPage")
    @ApiOperation(value = "分页及条件查询", notes = "用户列表")
    public Result findAllByPage(@RequestBody Map<String, String> param) {
        if (param == null || param.size() == 0) {
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        return Result.success(userService.findAllByPage(param));
    }


    @GetMapping("/findById/{id}")
    @ApiOperation(value = "根据id查询用", notes = "用户基本信息")
    @ApiImplicitParam(name = "id", value = "用户id", paramType = "path", required = true, dataType = "String")
    public Result findById(@PathVariable String id) { //@PathVariable 获取/get/{id}中id
        if (StringUtil.isEmpty(id)) {
            Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        return Result.success(userService.findById(id));
    }


    @DeleteMapping("/deleteById/{id}")
    @ApiOperation(value = "根据id删除数据", notes = "用户基本信息")
    @ControllerDesc(description = LogConstants.delete_data)
    @ApiImplicitParam(name = "id", value = "用户id", paramType = "path", required = true, dataType = "String")
    public Result deleteById(@PathVariable String id) { //@PathVariable 获取/get/{id}中id
        if (StringUtil.isEmpty(id)) {
            Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        return Result.success(userService.deleteById(id));
    }

    /**
     * 批量删除
     *
     * @param idList 主键集合
     * @return
     */
    @PostMapping("/deleteByIds")
    @ControllerDesc(description = LogConstants.delete_data)
    @ApiOperation(value = "批量删除", notes = "批量删除")
    public Result deleteByIds(@RequestBody List<String> idList) {
        //参数验证
        if (idList == null || idList.size() == 0) {
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        int count = userService.deleteByIds(idList);
        if (count == idList.size()) {
            return Result.success();
        }
        return Result.error(CodeMsg.DELETE_ERROR);
    }

    /**
     * 新增或修改
     *
     * @param tbUser 用户
     * @return
     */
    @PostMapping("/addOrUpdate")
    @ControllerDesc(description = LogConstants.addOrUpdate_data)
    @ApiOperation(value = "保存或修改", notes = "用户基本信息")
    public Result addOrUpdate(@RequestBody TbUser tbUser) {
        //参数验证
        if (tbUser == null) {
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        int count = userService.addOrUpdate(tbUser);
        if (count > 0) {
            return Result.success();
        }else if(count == -1){
            return Result.error(CodeMsg.DATA_REPEATE);
        }
        return Result.error(CodeMsg.INTER_ERROR);
    }


    /**
     * 给用户添加角色
     *
     * @param variables 用户和角色集合
     *                  userIds:用户ID集合
     *                  roleId:角色ID
     * @return
     */
    @PostMapping("/updateUser2Role")
    @ApiOperation(value = "给用户添加角色", notes = "用户和角色")
    public Result updateUser2Role(@RequestBody Map<String, Object> variables) {
        //参数验证
        if (variables == null || variables.size() == 0) {
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        if (variables.get("userIds") != null && variables.get("roleId") != null) {
            List<String> userIds = (List<String>) variables.get("userIds");
            String roleId = (String) variables.get("roleId");
            if (userIds.size() > 0 && StringUtil.isNotEmpty(roleId)) {
                int count = userService.updateUser2Role(userIds, roleId);
                if (count > 0) {
                    return Result.success();
                }
            }
        }
        return Result.error(CodeMsg.INTER_ERROR);
    }

    /**
     * 给用户添加角色
     *
     * @param variables 用户和角色集合
     *                  userIds:用户ID集合
     *                  groupId:部门ID
     * @return
     */
    @PostMapping("/updateUser2Group")
    @ApiOperation(value = "给用户添加部门", notes = "部门")
    public Result updateUser2Group(@RequestBody Map<String, Object> variables) {
        //参数验证
        if (variables == null || variables.size() == 0) {
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        if (variables.get("userIds") != null && variables.get("groupId") != null) {
            List<String> userIds = (List<String>) variables.get("userIds");
            String groupId = (String) variables.get("groupId");
            if (userIds.size() > 0 && StringUtil.isNotEmpty(groupId)) {
                int count = userService.updateUser2Group(userIds, groupId);
                if (count > 0) {
                    return Result.success();
                }
                return Result.success(CodeMsg.UPDATE_ERROR);
            }
        }
        return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
    }

    /**
     * 修改密码
     *
     * @param variables 用户
     *                  userId:用户id
     *                  oldPassword:旧密码
     *                  newPassword:新密码
     * @return
     */
    @PostMapping("/updatePassword")
    @ApiOperation(value = "修改密码", notes = "用户")
    public Result updatePassword(@RequestBody Map<String, String> variables) {
        //参数验证
        if (variables == null || variables.size() == 0) {
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        String oldPassword = variables.get("oldPassword");
        String newPassword = variables.get("newPassword");
        String userId = variables.get("userId");
        if (StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword)) {
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        } else {
            TbUser user = userService.findById(userId);
            if (user != null) {
                BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
                boolean flag = bcryptPasswordEncoder.matches(oldPassword,
                        user.getUserPassward().replace("{bcrypt}",""));
                if (!flag) {
                    return Result.error(CodeMsg.OLD_PASSWORD_ERR);
                }
                user.setUserPassward(newPassword);
                userService.addOrUpdate(user);
                return Result.success(CodeMsg.PASSWOR_RESET);
            }
            return Result.error(CodeMsg.DATA_NOT_EXIST);
        }

    }

    public static void main(String[] args) {
        String pass = "admin";
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        String hashPass = bcryptPasswordEncoder.encode(pass);
        System.out.println(hashPass);

        boolean f = bcryptPasswordEncoder.matches("admin",hashPass);
        System.out.println(f);

    }

}
